package config

import (
	"blog/app/model"
	"blog/core"
	"fmt"

	"gorm.io/gorm"
)

type Config struct {
}

// 设置参数
func (c Config) Set(group string, key string, value string) error {
	var count int64
	db := core.DbConnect.Model(model.Config{}).Scopes(condition{}.Select(group, key))
	if db.Count(&count); count > 0 {
		db.Update("value", value)
	} else {
		db.Create(model.Config{
			Group: group,
			Key:   key,
			Value: value,
		})
	}

	return db.Error
}

func (c Config) SetAll(group string, value map[string]string) {
	old := c.GetGroup(group)
	var update map[string]model.Config = make(map[string]model.Config)
	var create []model.Config = make([]model.Config, 0)
	fmt.Println(old)
	for k, v := range value {
		if _, ok := old[k]; ok {
			update[k] = model.Config{
				ID:    old[k].ID,
				Value: v,
			}
		} else {
			create = append(create, model.Config{
				Group: group,
				Key:   k,
				Value: v,
			})
		}
	}

	if len(update) > 0 {
		// TODO::应该可以优化的
		for _, v := range update {
			core.DbConnect.Model(model.Config{}).Where("id = ?", v.ID).Update("value", v.Value)
		}
	}

	if len(create) > 0 {
		core.DbConnect.Create(create)
	}
}

// 获得参数
func (c Config) Get(group string, key string) string {
	return ""
}

// 获得组配置
func (c Config) GetGroup(group string) map[string]model.Config {
	var lists []model.Config = make([]model.Config, 0)
	core.DbConnect.Model(model.Config{}).Select("id", "key", "value").Scopes(condition{}.SelectGroup(group)).Find(&lists)
	var m = make(map[string]model.Config)
	for _, v := range lists {
		m[v.Key] = v
	}
	return m
}

type condition struct {
}

func (c condition) Select(group string, key string) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		return db.Scopes(c.SelectGroup(group)).Where("key = ?", key)
	}
}

func (c condition) SelectGroup(group string) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		return db.Where("`group` = ?", group)
	}
}
